/* This file is part of swapper project
 *
 * Copyright (C) 2020 The Swapper Project Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.swapper.json.experimental.io;


import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
import java.util.Objects;


public final class _JsonReader implements Closeable {
  private final Reader reader;
  private int cursor;
  private int size;
  private final char[] buffer = new char[BUFFER_SIZE];
  private static final int BUFFER_SIZE = 2048;
  private static final int ROLLBACK_SIZE = 32;

  public _JsonReader(Reader in) {
    reader = Objects.requireNonNull(in);
  }

  private char next() throws IOException {
    if (cursor >= size) {
      if (size == 0) {
        size = reader.read(buffer);
        if (size == -1) {
          throw new EOFException("The input stream is empty.");
        }
      } else {
        int start = cursor - ROLLBACK_SIZE;
        int length = BUFFER_SIZE - start;
        System.arraycopy(buffer, start, buffer, 0, length);
        size = reader.read(buffer, length, BUFFER_SIZE - length);
        if (size == -1) {
//          if (!path.isEmpty()) {
//            throw new EOFException("The input stream ends before full parsing.");
//          }
          return '\u0000';
        }
        size += cursor = length;
      }
    }
    return buffer[cursor++];
  }


  @Override
  public void close() throws IOException {
    reader.close();
  }

  @Override
  public String toString() {
    return reader.toString();
  }
}
